package com.cwz.datasource.dynamic.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.cwz.core.utils.string.StringUtils;
import com.cwz.datasource.dynamic.utils.DataSourceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: w-demo
 * @description: 基础数据源实现类
 * @author: Wen
 **/
@Slf4j
@Configuration
public class BaseDataSourceInit {
	@Autowired
	private DefaultDataSourceProperties defaultDataSourceProperties;
	private static DruidDataSource singleBaseDataSource = null;

	@Bean
	public DynamicRoutingDataSource dynamicRoutingDataSource() throws SQLException {
		DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
		DruidDataSource singleBaseDataSource = getSingleBaseDataSource();
		dynamicRoutingDataSource.setDefaultTargetDataSource(singleBaseDataSource);

		Map<Object, Object> dataSourceMap = new HashMap<>(16);
		dataSourceMap.put("baseDatasource", singleBaseDataSource);
		dynamicRoutingDataSource.setTargetDataSources(dataSourceMap);
		dynamicRoutingDataSource.afterPropertiesSet();
		return dynamicRoutingDataSource;
	}

	private DruidDataSource getSingleBaseDataSource() throws SQLException {
		if (StringUtils.isNotNull(singleBaseDataSource)) {
			return singleBaseDataSource;
		}
		singleBaseDataSource = new DruidDataSource();
		DataSourceUtils.setDruidDataSource(singleBaseDataSource, defaultDataSourceProperties);
		return singleBaseDataSource;
	}
}
